<template>
  <div>
    <n-data-table
      remote
      ref="table"
      :columns="columns"
      :data="data"
      :pagination="pagination"
      :loading="loading"
    />
  </div>
</template>

<script setup lang="ts">
import { NButton, NDataTable, NTag, type DataTableColumn, useDialog } from 'naive-ui'
import { GetUserListApi, DelteUserApi } from '@/apis/user'
import { ref, onMounted, h } from 'vue'

const dialog = useDialog()
const loading = ref<boolean>(true)
const pagination = ref({
  page: 1,
  pageCount: 2,
  pageSize: 10
})
const columns = ref<DataTableColumn[]>([
  {
    title: 'ID',
    key: 'id'
  },
  {
    title: '姓名',
    key: 'profile.name'
  },
  {
    title: '电话号码',
    key: 'phone'
  },
  {
    title: '年级',
    key: 'profile.grade'
  },
  {
    title: '班级',
    key: 'profile.class'
  },
  {
    title: '所属部门',
    key: 'profile.department',
    render(row: any) {
      return h(
        NTag,
        {
          type: 'info'
        },
        {
          default: () => row.profile.department
        }
      )
    }
  },
  {
    title: '用户组',
    key: 'group.name'
  },
  {
    title: '更新时间',
    key: 'update_time'
  },
  {
    title: '操作',
    key: 'action',
    render(row) {
      const actions = [
        h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            class: 'mr-1',
            onClick: () => {
              console.log(row.id)
            }
          },
          {
            default: () => '编辑'
          }
        ),
        h(
          NButton,
          {
            type: 'error',
            size: 'small',
            class: 'mr-1',
            onClick: () => {
              DeleteUset(row)
            }
          },
          {
            default: () => '删除'
          }
        )
      ]
      return actions
    }
  }
])
const data = ref<any[]>([])

function DeleteUset(user: any) {
  dialog.warning({
    title: '警告',
    content: `确定删除 ${user.profile.name} 用户吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await DelteUserApi(user.id)
        loadData()
        window.$message.success('删除成功')
      } catch (error) {
        window.$message.error(error as string)
      }
    }
  })
}


function loadData(){
  GetUserListApi().then((res) => {
    data.value = res as unknown as any[]
    loading.value = false
  })
}


onMounted(() => {
  loadData()
})
</script>
